<?php
/**
 * @Notes: 文件描述
 * @Interface getCondition
 * @Return mixed
 * @Author: fc
 * @Time: 2021/4/20 18:11
 */

namespace app\common\service;

use elasticsearch\Elasticsearch;
use Bluerhinos\phpMQTT as MqttClient;

class EsTool
{

    /**
     * 获取ES数据，类似 DSL中的_search请求
     */
    public function getSource()
    {
        // $where = array(
        //     'cdate' => 20180722,
        //     'status,neq' => 0,
        //     "reserve_end_time,lte" => date("Y-m-d"),
        //     "create_time,gte" => "2016-08-13",
        // );

        $where = array(
            'goods_name,match' => '12'
        );

        $result = Elasticsearch::getInstanceNew()
            ->setIndexMapping("products_test")
            ->setWhere($where)
            ->setSource(array("id", "goods_name", "state", "class_id", "single_goods_name", "goods_sort", "price", "_score"))
            ->setSize(5)
            ->setFrom(0)
            ->query()
            ->fetchTableSource();

        return $result;
    }

    /**
     * 脚本评分方法
     */
    public function getScript()
    {
        // $where = array(
        //     'cdate' => 20180722,
        //     'status,neq' => 0,
        //     "reserve_end_time,lte" => date("Y-m-d"),
        //     "create_time,gte" => "2016-08-13",
        // );
        $where = array(
            'goods_name,match' => '1'
        );
        $sortFields = array(
            'goods_sort'
        );
        $sortWight = array();
        foreach ($sortFields as $key) {
            $sortWight[$key] = rand(1, 10);
        }
        $result = Elasticsearch::getInstanceNew()
            ->setIndexMapping("products_test")
            ->setWhere($where)
            ->setScoreFieldsWight($sortWight)
            ->setSource(array("id", "goods_name", "state", "class_id", "single_goods_name", "goods_sort", "price", "_score"))
            ->setSize(5)
            ->setFrom(0)
            ->query()
            ->fetchTableSource();
        return $result;
    }

    /**
     * 获取聚合查询结果
     * @desc es聚合方法
     * @copyright 0.1
     */
    public function getAggs()
    {
        // $where = array(
        //     'cdate' => 20180722,
        //     'status,neq' => 0,
        //     "reserve_end_time,lte" => date("Y-m-d"),
        //     "create_time" => array("2018-07-01", "2018-07-10"),
        //     "category_name,in" => array("休闲益智", "体育", "塔防"),
        // );

        $where = array(
            'goods_name,match' => '苹果'
        );

        $result = Elasticsearch::getInstanceNew()
            ->setParam(
                $where,
                array("id"),
                array("goods_name" => array("size" => 10)),
                array("goods_name" => array("show_field" => "goods_name", "size" => 5))
            )
            ->setParam($where, ["id", "goods_name", "single_goods_name", "goods_sort"], [], [])
            ->setIndexMapping("products_test")
            ->query()
            ->fetchTable();

        return $result;
    }

}